package br.com.nirvana.loteria.input;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import br.com.nirvana.loteria.exception.DownloadException;
import br.com.nirvana.loteria.util.PropertiesUtil;

public class Download {

	public void downloadFile(String downloadURL, String fileName)
			throws DownloadException {
		System.out.println("Downloading '" + "' from '" + downloadURL + "'.");
		String downloadFolder = PropertiesUtil.getLoteriaProperties()
				.getProperty("download_folder");

		try {
			BufferedInputStream in = new java.io.BufferedInputStream(
					new java.net.URL(downloadURL).openStream());

			FileOutputStream fos = new java.io.FileOutputStream(new File(
					downloadFolder, fileName));

			BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

			byte[] data = new byte[1024];
			int x = 0;
			while ((x = in.read(data, 0, 1024)) >= 0) {
				bout.write(data, 0, x);
			}
			bout.close();
			in.close();
		} catch (MalformedURLException e) {
			throw new DownloadException(e);
		} catch (IOException e) {
			throw new DownloadException(e);
		}
		System.out.println("Download complete.");
	}

}
